package com.renwei.yunlong.fragment;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.CompanyInfoActivity;
import com.renwei.yunlong.activity.me.DisplayEnterpriseInfoActivity;
import com.renwei.yunlong.activity.me.EnterpriseInformationActivity;
import com.renwei.yunlong.activity.me.InformationActivity;
import com.renwei.yunlong.activity.me.SettingActivity;
import com.renwei.yunlong.activity.me.ShareActivity;
import com.renwei.yunlong.activity.news.MessageCompanyActivity;
import com.renwei.yunlong.activity.work.HelpActivity;
import com.renwei.yunlong.activity.work.SearchActivity;
import com.renwei.yunlong.base.BaseLazyFragment;
import com.renwei.yunlong.bean.Company;
import com.renwei.yunlong.bean.InformationBean;
import com.renwei.yunlong.bean.MsgCompanyBean;
import com.renwei.yunlong.bean.OtherCompanyBean;
import com.renwei.yunlong.event.MinePageRefreshEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.global.EventKey;
import com.renwei.yunlong.global.IntentKey;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.qrcode.SimpleCaptureActivity;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.view.RatingBar;
import com.renwei.yunlong.view.RoundImageView;

import java.util.HashMap;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 我的--Fragment
 * <p>
 * Created by Administrator on 2017/8/24.
 */

public class MeFragment extends BaseLazyFragment implements View.OnClickListener, HttpTaskListener {
    private static final String TAG = "MeFragment---:";
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.iv_head)
    RoundImageView ivHead;
    @Bind(R.id.iv_enter)
    ImageView ivEnter;
    @Bind(R.id.tv_nickname)
    TextView tvNickname;
    @Bind(R.id.rtb_star_fives)
    RatingBar rtbStarFives;
    @Bind(R.id.tv_star_count)
    TextView tvStarCount;
    @Bind(R.id.tv_job_number)
    TextView tvJobNumber;
    @Bind(R.id.tv_work_number)
    TextView tvWorkNumber;
    @Bind(R.id.rl_next)
    RelativeLayout rlNext;
    @Bind(R.id.iv_enterprise)
    ImageView ivEnterprise;
    @Bind(R.id.rl_enterprise)
    RelativeLayout rlEnterprise;
    @Bind(R.id.iv_scanner)
    ImageView ivScanner;
    @Bind(R.id.rl_scaner)
    RelativeLayout rlScaner;
    @Bind(R.id.iv_search)
    ImageView ivSearch;
    @Bind(R.id.rl_search)
    RelativeLayout rlSearch;
    @Bind(R.id.rl_help)
    RelativeLayout rlHelp;
    @Bind(R.id.iv_share)
    ImageView ivShare;
    @Bind(R.id.rl_share)
    RelativeLayout rlShare;
    @Bind(R.id.iv_setting)
    ImageView ivSetting;
    @Bind(R.id.rl_setting)
    RelativeLayout rlSetting;
    @Bind(R.id.rl_invite)
    RelativeLayout rlInvite;
    @Bind(R.id.tv_bar_invite)
    TextView tvBarInvite;
    private boolean isAdmin = false;

    private Intent intent;
    private boolean isLoadMsgCount;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.fragment_me;
    }

    @Override
    public void onLazyLoad() {
        tvTitle.setText("我");
        ivBack.setVisibility(View.GONE);
        tvRight.setVisibility(View.GONE);
        rtbStarFives.setFocusable(false);
        rtbStarFives.setClickable(false);
        rlNext.setOnClickListener(this);
        rlEnterprise.setOnClickListener(this);
        rlSearch.setOnClickListener(this);
        rlShare.setOnClickListener(this);
        rlSetting.setOnClickListener(this);
        rlScaner.setOnClickListener(this);
        rlHelp.setOnClickListener(this);
        rlInvite.setOnClickListener(this);

        reqUserInfo();
    }


    private void reqUserInfo() {//请求用户信息
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        HashMap map = new HashMap();
        if ("1".equals(companyType)) {
            if (ownerBean.getRows() != null) {
                map.put("employeeId", ownerBean.getRows().getEmployeeId());
                manager.QueryInfomationByEmployeeId(getActivity(), "1", JsonMapUtil.mapToJson(map), this);
                Log.e("业主 个人信息jsonBean", JsonMapUtil.mapToJson(map));
            }
        } else if ("2".equals(companyType)) {
            if (serviceLoginBean.getRows() != null) {
                map.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
                manager.QueryInfomationByEmployeeId(getActivity(), "2", JsonMapUtil.mapToJson(map), this);
                Log.e("服务商 个人信息jsonBean", JsonMapUtil.mapToJson(map));
            }
        }
        if ("1".equals(companyType)) {
            isAdmin = AppHelper.isAdminDesk(ownerBean);
        } else {
            isAdmin = AppHelper.isAdminDesk(serviceLoginBean);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            if (isLoadMsgCount) {
                initCompanyMsg();
            }
            refreshMcache();
            reqUserInfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            if (isLoadMsgCount) {
                initCompanyMsg();
            }
            refreshMcache();
            reqUserInfo();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_next://人员信息
                intent = new Intent(getActivity(), InformationActivity.class);
                intent.putExtra("type", "me");
                startActivity(intent);
                break;
            case R.id.rl_enterprise://企业信息
                intent = new Intent(getActivity(), EnterpriseInformationActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_search://查询
                intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_help: // 帮助中心
                HelpActivity.OpenActivity(getContext());
                break;
            case R.id.rl_share://分享
                intent = new Intent(getActivity(), ShareActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_setting://设置
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivityForResult(intent, 111);
                break;
            case R.id.rl_scaner://扫描
                SimpleCaptureActivity.openSannerActivity(this, IntentKey.ME_SANNER);
                break;
            case R.id.rl_invite:
                MessageCompanyActivity.OpenActivity(getContext());
                break;
            default:
                break;
        }
    }

    private void initCompanyMsg() {
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("receiverCompanyCode", ownerBean.getRows().getOwnerCode());
        } else if ("2".equals(companyType)) {
            map.put("receiverCompanyCode", serviceLoginBean.getRows().getServiceProviderCode());
        }
        manager.getCompanyMsgCount(getActivity(), JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 3:
                Log.e("业主返回个人信息", result);
                InformationBean bean = new Gson().fromJson(result, InformationBean.class);
                if (bean.getMessage().getCode() == 200) {//加载成功
                    //头像路径
                    if (StringUtils.value(bean.getRows().getAvatar()).length() > 0) {
                        Glide.with(getContext()).load(Api.$().OWNER_FILE_URL + bean.getRows().getAvatar())
                                .error(R.mipmap.icon_header_default).into(ivHead);
                    }
                    tvNickname.setText(bean.getRows().getName());
                    tvJobNumber.setText(String.valueOf("工号 " + StringUtils.value(bean.getRows().getEmployeeCode())));
                    tvWorkNumber.setText(String.valueOf("已经解决工单 " + StringUtils.value(bean.getRows().getWorkOrderNumber())));
                    String lock = String.valueOf(bean.getRows().getLock()).length() == 0 ? "0" : String.valueOf(bean.getRows().getLock());
                    rtbStarFives.setStar(Float.parseFloat(lock));
                    tvStarCount.setText(lock);
                    LogUtil.e("isadminordesk+me" + isAdmin);
                    if (isAdmin) {
                        rlInvite.setVisibility(View.VISIBLE);
                        isLoadMsgCount = true;
                    } else {
                        rlInvite.setVisibility(View.GONE);
                        isLoadMsgCount = false;
                    }
                }
                break;
            case 4:
                Log.e("服务商返回个人信息", result);
                InformationBean serviceBean = new Gson().fromJson(result, InformationBean.class);
                if (serviceBean.getMessage().getCode() == 200) {
                    //头像路径
                    if (StringUtils.value(serviceBean.getRows().getAvatar()).length() > 0) {
                        Glide.with(getContext()).load(Api.$().SERVICE_FILE_URL + serviceBean.getRows().getAvatar())
                                .error(R.mipmap.icon_header_default).into(ivHead);
                    }
                    tvNickname.setText(StringUtils.value(serviceBean.getRows().getName()));
                    tvJobNumber.setText(String.valueOf("工号 " + StringUtils.value(serviceBean.getRows().getEmployeeCode())));
                    tvWorkNumber.setText(String.valueOf("已经解决工单 " + StringUtils.value(serviceBean.getRows().getWorkOrderNumber())));
                    String lock = String.valueOf(serviceBean.getRows().getLock()).length() == 0 ? "0" : String.valueOf(serviceBean.getRows().getLock());
                    rtbStarFives.setStar(Float.parseFloat(lock));
                    tvStarCount.setText(lock);
                    if (isAdmin) {
                        rlInvite.setVisibility(View.VISIBLE);
                        isLoadMsgCount = true;
                    } else {
                        rlInvite.setVisibility(View.GONE);
                        isLoadMsgCount = false;
                    }
                }
                break;
            case 666:
                MsgCompanyBean msgBean = new Gson().fromJson(result, MsgCompanyBean.class);
                if (msgBean != null && msgBean.getRows() != null) {
                    CommonUtils.setBarTextView(tvBarInvite, msgBean.getRows().getQuantity());
                }
                break;
            case 880://扫描二维码查询相关信息
                OtherCompanyBean companyBean = new Gson().fromJson(result, OtherCompanyBean.class);
                if (companyBean != null) {
                    if (companyBean.getCompany() != null) {
                        doCompareCompany(companyBean.getCompany());
                    } else {
                        showCenterInfoMsg("没有查询到相关企业信息");
                    }
                } else {
                    showCenterInfoMsg("没有查询到相关企业信息");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getContext().getResources().getString(R.string.net_work_error));
    }

    //比较企业信息
    public void doCompareCompany(Company company) {
        String flag = StringUtils.value(AppHelper.getMyCompanyInfo().getRows().getCheckFlag());
        if (!"2".equals(StringUtils.value(flag))) {
            showCenterInfoMsg("贵公司尚未认证,无法添加企业好友");
            return;
        }
        if (company != null) {
            //  showCenterInfoMsg("isBing:" + StringUtils.value(company.getIsBing()));
            String targetCompanyType = StringUtils.value(company.getType());
            if ("1".equals(companyType) && companyType.equals(targetCompanyType)) {
                showCenterInfoMsg("贵公司作为业主,只能邀请服务商成为好友企业");
                return;
            } else if ("2".equals(companyType)
                    && companyType.equals(targetCompanyType)) {
                showCenterInfoMsg("贵公司作为服务商,只能邀请业主成为好友企业");
                return;
            } else if (!"2".equals(company.getCheckFlag())) {
                showCenterInfoMsg("对方还未认证,不能发送邀请");
                return;
            } else if ("0".equals(StringUtils.value(company.getIsBing()))) {
                CompanyInfoActivity.OpenActivity(getActivity(), company, "");
                //不是企业好友打开信息页面
            } else {
                DisplayEnterpriseInfoActivity.OpenActivity(getActivity(), StringUtils.value(company.getCompanyCode()));
            }//是企业好友查看很多资料的企业详情
        }
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(MinePageRefreshEvent event) {
        LogUtil.e(TAG + "eventmessage ：" + event.getMessage());
        switch (event.getMessage()) {
            case EventKey.UPDATE_USER_INFO:
                refreshMcache();
                reqUserInfo();
                break;
            default:
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && data.getStringExtra("result") != null) {
            LogUtil.e("二维码扫描" + StringUtils.value(data.getStringExtra("result")));
            switch (requestCode) {
                case IntentKey.ME_SANNER:
                    if (data != null && data.getStringExtra("result") != null) {
                        ServiceRequestManager manager = ServiceRequestManager.getManager();
                        String result = StringUtils.value(data.getStringExtra("result"));
                        HashMap<String, String> map = new HashMap<>();
                        map.put("isBingCompanyCode", StringUtils.value(getCompanyCode()));
                        map.put("companyCode", StringUtils.value(result));
                        manager.ScanCompanyQRcode(getActivity(), JsonMapUtil.mapToJson(map), this);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}

